<template>
  <div v-loading="loading" style="padding: 10px 20px 0 20px">
    <div style="display: flex; align-items: center; margin-bottom: 10px">
      <div style="" class="queryDivClass">
        <div class="inputLeftClass" style="border-left: none">
          <span>分类目录</span>
        </div>
        <el-select
          v-model="requestEntity.fldm"
          @change="getList"
          placeholder=""
          size="small"
          style="width: 395px"
          filterable
        >
          <el-option
            v-for="item in dmflList"
            :key="item.fldm"
            :label="item.flmc"
            :value="item.fldm"
          >
            <span style="float: left">{{ item.fldm }}</span>
            <span
              style="
                float: right;
                color: var(--el-text-color-secondary);
                font-size: 13px;
                margin-right: 15px;
              "
            >
              {{ item.flmc }}
            </span>
          </el-option>
        </el-select>
      </div>
      <div style="margin-left: auto; display: flex; align-items: center">
        <el-checkbox-group
          v-model="requestEntity.dmList"
          size="small"
          style="margin-right: 20px"
          @change="getList('reset')"
        >
          <el-checkbox label="已对码" value="ydm" />
          <el-checkbox label="未对码" value="wdm" />
        </el-checkbox-group>
        <div style="" class="queryDivClass">
          <div class="inputLeftClass" style="border-left: none">
            <span>检索码</span>
          </div>
          <el-input
            size="small"
            v-model="requestEntity.jsm"
            style="width: 150px"
            clearable
            placeholder="关键字"
          />
        </div>

        <el-button
          size="small"
          type="primary"
          @click="getList('reset')"
          style="margin-left: 5px"
          icon="Search"
          >查询
        </el-button>
        <el-button
          size="small"
          type="primary"
          @click="onSyncData"
          style="margin-left: 5px"
          icon="Coin"
          >数据同步
        </el-button>
      </div>
    </div>

    <div style="height: 100%">
      <div>
        <el-table
          class="tableClass"
          style="width: 100%"
          :row-class-name="rowStyle"
          size="small"
          :stripe="true"
          border
          :data="tableList.list"
          highlight-current-row
          @current-change="selectCurrentChange($event)"
          ref="tableRef"
        >
          <el-table-column type="index" width="35" align="center" />
          <el-table-column
            v-for="(column, columnIndex) in tableList.columnList"
            :prop="column.prop"
            :label="column.label"
            :min-width="column.width"
            header-align="center"
            align="center"
            :show-overflow-tooltip="column.prop !== 'mldm' && column.prop !== 'mlmc'"
          >
            <template #default="scope">
              <div v-if="column.prop === 'mldm'">
                <el-input
                  ref="mldmInputRef"
                  v-model="scope.row.mldm"
                  @blur="mldmBlur(scope.row)"
                  @keydown.enter="openSelectTips(scope.row)"
                  @click="mldmClick(scope.row)"
                  size="small"
                >
                </el-input>
              </div>
              <div v-else>{{ scope.row[column.prop] }}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="openSaveCode(scope.row)" link
                >手动录入</el-button
              >
              <el-button type="danger" size="small" @click="openDelete(scope.row)" link
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="margin-top: 5px; margin-bottom: 5px">
        <el-pagination
          v-model:current-page="requestEntity.pageNumber"
          v-model:page-size="requestEntity.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          :size="'small'"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableList.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div style="">
      <MatchingCodesTips ref="matchingCodesTipsRef" @getList="getList" />
    </div>
    <div>
      <el-dialog v-model="updateTips" title="手动录入" width="400" align-center>
        <div style="display: grid">
          <el-form
            label-width="auto"
            size="small"
            class="fromClass"
            ref="ruleFormRef"
            :rules="rules"
            :model="saveEntity"
          >
            <el-form-item label="对码代码" prop="mldm">
              <el-input v-model="saveEntity.mldm" />
            </el-form-item>
            <el-form-item label="对码名称" prop="mlmc">
              <el-input v-model="saveEntity.mlmc" />
            </el-form-item>
          </el-form>
          <div style="margin-left: auto">
            <el-button @click="onSaveCode" type="primary" size="small">保存</el-button>
            <el-button @click="updateTips = false" size="small">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { isBlank, isNotBlank, isNotEmpty, listToMap } from '@utils/util'
import MatchingCodesTips from '@coms/MatchingCodesTips.vue'
import { deleteTydm, getFlmlList, getHismlList, getTydmSjtb } from '@api'
import type { FormRules } from 'element-plus'

const saveEntity = ref({
  beiz: '',
  mldm: null,
  mlmc: ''
} as any)
const ruleFormRef = ref<any>()
const rules: FormRules = {
  mldm: [{ required: true, message: '请输入代码', trigger: 'blur' }],
  mlmc: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}
const updateTips = ref(false)
const matchingCodesTipsRef = ref()
const mldmInputRef = ref()
const dmflList = ref([] as any[])
const requestEntity = ref({
  jsm: '',
  dmList: ['wdm'],
  fldm: '',
  pageNumber: 1,
  pageSize: 30
} as any)
interface ColumnListItem {
  prop: string
  label: string
  width: string
}
const userInfo = ref({} as any)
const loading = ref(false)
const tableRef = ref()
const tableList = ref<{
  columnList: ColumnListItem[]
  list: any[]
  total: number
}>({
  columnList: [
    // {prop: 'name', label: '姓名', width: '100'},
    // {prop: 'date', label: '时间', width: '200'},
    // {prop: 'mldm', label: '对码代码', width: '200'},
  ],
  list: [
    // {name: '张三', date: new Date(), mldm: '12345'}
  ] as any[],
  total: 0
})

const rowStyle = (rowStyle: any) => {
  return ''
}

const mldmClick = (row: any) => {
  // console.log(JSON.stringify(row))
  if (isBlank(row.mldm)) {
    row.mldm =
      `${row?.mc?.slice(0, 4) || ''} ${row?.gg?.slice(0, 3) || ''} ${row?.cd?.slice(0, 4) || ''}`.trim()
  } else {
    // 暂存一下上一次点击输入框的值
    row.old_mldm = row.mldm
  }
}
const mldmBlur = (row: any) => {
  // console.log(JSON.stringify(row), isBlank(row.mlmc))
  // mlmc 是空的，说明这个只是搜索还没有绑码，自动清空搜索值
  if (isBlank(row.mlmc)) {
    row.mldm = null
  } else {
    // 如果绑码了，失去焦点以后恢复成之前的值
    row.mldm = row.old_mldm
  }
}
const openSelectTips = async (row: any) => {
  row.fldm = requestEntity.value.fldm
  let propMap = listToMap(tableList.value.columnList, 'prop')
  row.parentVo = {
    key1: { label: propMap['mc']?.label, value: row['mc'] },
    key2: { label: propMap['gg']?.label, value: row['gg'] },
    key3: { label: propMap['cd']?.label, value: row['cd'] }
  }
  if (isBlank(userInfo.value.jgid)) {
    console.error('userInfo jgid 为空')
  }
  // 打开对码弹窗
  await matchingCodesTipsRef.value.openCheckTips(row, userInfo.value)
}
const openSaveCode = (row: any) => {
  saveEntity.value = {}
  // console.log(JSON.stringify(row))
  Object.assign(saveEntity.value, row)
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate() // 清除校验
  }

  updateTips.value = true
}
const onSaveCode = async () => {
  ruleFormRef.value.validate(async (valid: any, fields: any) => {
    if (valid) {
      // console.log('en', JSON.stringify(saveEntity.value))
      await matchingCodesTipsRef.value.saveCode({
        jgid: userInfo.value.jgid,
        fldm: requestEntity.value.fldm,
        his_id: saveEntity.value.id,
        his_mc: saveEntity.value.mc,
        mldm: saveEntity.value.mldm,
        mlmc: saveEntity.value.mlmc,
        beiz: saveEntity.value.beiz,
        cjrid: userInfo.value.rid || userInfo.value.zhid,
        cjrxm: userInfo.value.rxm || userInfo.value.zh
        // cjsj: null,
      })
      setTimeout(() => {
        updateTips.value = false
      }, 200)
    }
  })
}
const openDelete = async (row: any) => {
  // console.log(JSON.stringify(row))
  if (isNotBlank(row.his_id) && isNotBlank(row.jgid)) {
      ElMessageBox.confirm(
          '您确认删除该条数据【对码信息】吗?',
          '提醒',
          {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
          } as any
      ).then(() => {
          deleteTydm({data: {jgid: row.jgid, his_id: row.his_id, fldm: requestEntity.value.fldm}})
          ElMessage.success("删除成功！")
          getList(null)
      }).catch(() => {
      })

  }
}

const selectCurrentChange = (row: any) => {
  if (isBlank(row?.id)) {
    return
  }
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 100)
}
const getList = async (query: any) => {
  loading.value = true
  // 药品分类类型根据tab同步
  if (query) {
    // 如果点击的查询，要把分页重置成默认值
    requestEntity.value.pageNumber = 1
    requestEntity.value.pageSize = 30
  }
  // 一个都不选 或者 两个全选就传入 null 查询全部，选了一个 就传对应的值
  requestEntity.value.dm =
    isNotEmpty(requestEntity.value.dmList) && requestEntity.value.dmList.length === 1
      ? requestEntity.value.dmList[0]
      : null
  requestEntity.value.jgid = userInfo.value.jgid
  let hisListRes = await getHismlList({ data: requestEntity.value })
  if (hisListRes.code === 1) {
    tableList.value = hisListRes.data as any

    tableList.value.list.forEach((item: any) => {
      item.old_mldm = item.mldm
    })
    setTimeout(() => {
      loading.value = false
    }, 100)
  }
}
const onSyncData = async () => {
  let hisListRes = await getTydmSjtb({ data: requestEntity.value.fldm })
  if (hisListRes.code === 1) {
    console.log('同步完成')
  } else {
    console.log('同步失败')
  }
}
import {useUserStore} from "@ui/vue/store/user";

onBeforeUnmount(() => {
})
onMounted(async () => {
    const magicUserInfo = useUserStore().getUserInfo;
    console.log('userInfo', magicUserInfo)
    Object.assign(userInfo.value, magicUserInfo)

    getFlmlList({data: {jgid: userInfo.value.jgid}}).then((res: any) => {
        if (isNotEmpty(res?.data)) {
            dmflList.value = res?.data as any

            requestEntity.value.fldm = dmflList.value[0].fldm

            getList(null)
        }
    })
})
const handleSizeChange = (val: number) => {
  requestEntity.value.pageSize = val
  getList(null)
}
const handleCurrentChange = (val: number) => {
  requestEntity.value.pageNumber = val
  getList(null)
}
</script>

<style scoped lang="scss">
.radioButtonClass {
  :deep(.el-radio-button__inner) {
    border-radius: 0 !important;
    font-size: 11px;
  }
}

.tableClass {
  height: calc(100vh - 80px);
  user-select: text;
  -webkit-user-select: text; // 2个效果一样都是为了让能复制文本，-webkit-user-select 这个是为了兼容旧的浏览器
  --el-table-current-row-bg-color: #c6e2ff !important; // 选中的默认蓝色
  --el-table-border-color: var(--el-border-color-lighter) !important;

  :deep(.el-table__body tr:hover > td) {
    background-color: #d9ecff !important;
  }

  :deep(.el-table__body) {
    color: #000000;
    cursor: text;
  }
}

.queryDivClass {
  display: flex;
  align-items: center;
  color: #666666;
  font-size: 11px;
  border: 1px solid #dcdfe6;

  :deep(.el-input) {
    --el-input-focus-border-color: #409eff; // 选中时的颜色
    //--el-input-hover-border-color: #dedfe0;// 鼠标聚焦时的颜色
    --el-input-border-color: #ffffff; // 默认颜色白色，相当于隐藏了边框
  }

  :deep(.el-input--small .el-input__wrapper) {
    padding: 1px 4px;
  }

  :deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #ffffff inset;
  }

  :deep(.el-select__wrapper.is-focused) {
    box-shadow: 0 0 0 1px #409eff inset;
  }

  :deep(.el-date-editor.el-input__wrapper) {
    box-shadow: 0 0 0 1px #ffffff inset;
  }

  :deep(.el-range-editor.is-active:hover) {
    box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset !important;
  }

  :deep(.el-range-editor.is-active) {
    box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset !important;
  }
}

.gytjClass {
  :deep(.el-select--small .el-select__wrapper) {
    min-height: 26px;
  }
}

.gydwClass {
  display: flex;
  align-items: center;
  color: #666666;
  font-size: 11px;
  border: 1px solid #dcdfe6;

  :deep(.el-input) {
    --el-input-focus-border-color: #409eff; // 选中时的颜色
    //--el-input-hover-border-color: #dedfe0;// 鼠标聚焦时的颜色
    --el-input-border-color: #ffffff; // 默认颜色白色，相当于隐藏了边框
  }

  :deep(.el-input--small .el-input__wrapper) {
    padding: 1px 4px;
  }

  :deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #ffffff inset;
  }

  :deep(.el-select__wrapper.is-focused) {
    box-shadow: 0 0 0 1px #409eff inset;
  }

  :deep(.el-button) {
    border: none !important;
  }
}

.inputLeftClass {
  background-color: #f2f3f5;
  border-right: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  height: 24px;
  width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.tableRowStyle) {
  color: red;
}

:deep(.tableRowStyle1) {
  //background: #F0F8EB;
  //background: #a0cfff;
  color: #409eff;
}

:deep(.cxTableRowStyle) {
  background: #faecd8;
}

//:deep(.el-input .el-input--small .el-input-group .el-input-group--prepend) {
//  border-radius: 0 !important;
//}

:deep(.el-select__wrapper) {
  border-radius: 0 !important;
}

:deep(.el-input__wrapper) {
  border-radius: 0 !important;
}

:deep(.el-button) {
  border-radius: 0 !important;
}
</style>
